﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace DynamicChart.Service.Step.Format;

public class YAxisStep : IFormatStep
{
    public void Process(IDictionary<string, object> param, IDictionary<string, object> data)
    {
        var series = data["series"] as List<Dictionary<string, object>>;
        var validSeries = series
            .Where(item => item["data"] is List<object> dataList && dataList.Count > 0)
            .Select(item => ((List<object>)item["data"]).ToList())
            .ToList();

        var groupedData = validSeries
            .GroupBy(data => data[0]?.GetType().ToString())
            .Select(g => new
            {
                AllData = g.SelectMany(x => x).Distinct().ToList(),
                Position = g.Key
            })
            .ToList();

        var yAxis = groupedData.Select((g, index) => new Dictionary<string, object>
        {
            ["type"] = "value",
            ["position"] = index == 0 ? "left" : "right",
            ["min"] = BeautifyValue(Convert.ToDouble(g.AllData.Min()) - 2 * ((Convert.ToDouble(g.AllData.Max()) - Convert.ToDouble(g.AllData.Min())) / g.AllData.Count)),
            ["max"] = BeautifyValue(Convert.ToDouble(g.AllData.Max()) + 2 * ((Convert.ToDouble(g.AllData.Max()) - Convert.ToDouble(g.AllData.Min())) / g.AllData.Count)),
            ["interval"] = BeautifyValue((Convert.ToDouble(g.AllData.Max()) - Convert.ToDouble(g.AllData.Min())) / g.AllData.Count)
        }).ToList();

        data["yAxis"] = yAxis;
    }

    private double BeautifyValue(double value)  
    {
        if (value < 0)
        {
            return 0;
        }
        
        return Math.Round(value);
    }
}